from django.shortcuts import render
from django.utils import timezone
from rest_framework.filters import OrderingFilter

from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView
from rest_framework.pagination import PageNumberPagination

from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView

from spit.models import Spit, SpitComments, SpitLike, CommentsLike
from spit.serializers import SpitListSerializer, SpitDetailSerializer, SpitCommentsListSerializer, \
    SpitCollectionsSerializer


# Create your views here.


# 分页
class LargeResultsSetPagination(PageNumberPagination):
    page_size = 8
    page_size_query_param = 'page_size'
    max_page_size = 20


class SpitListView(ListAPIView):
    """吐槽首页"""
    serializer_class = SpitListSerializer
    queryset = Spit.objects.all().order_by('-like_count')
    pagination_class = LargeResultsSetPagination


class SpitDetailView(RetrieveAPIView):
    """吐槽详情页"""
    serializer_class = SpitDetailSerializer
    queryset = Spit.objects.all()


class SpitCommentsListView(ListAPIView):
    """吐槽详情页评论列表"""
    serializer_class = SpitCommentsListSerializer

    def get_queryset(self):
        # 获取当前吐槽的全部评论
        id = self.kwargs['spit_id']
        return SpitComments.objects.filter(spit_id=id).order_by('-create_time',)


class SpitSubmitView(APIView):
    """发布吐槽"""
    def post(self, request):
        # 获取参数
        data = request.data
        author_id = data['user_id']
        # 生成时间
        time = timezone.now().strftime('%Y-%m-%d %H:%M:%S')

        # 校验参数
        # 校验成功，保存
        if len(data['content']) <= 140:
            # 将吐槽内容保存到数据库中
            spit = Spit()
            spit.author_id = author_id
            spit.create_time = time
            spit.content = data['content']
            spit.save()
            return Response({'msg': '发布成功'}, status=status.HTTP_201_CREATED)
        # 校验失败
        else:
            return Response({'msg': '超过最大字符数'})


class SpitCommentCreateView(APIView):
    """评论吐槽"""
    def post(self,request):
        # 获取参数
        data = request.data
        author_id = int(request.query_params['user_id'])
        spit_id = int(request.query_params['spit_id'])

        # 生成时间
        time = timezone.now().strftime('%Y-%m-%d %H:%M:%S')

        # 将评论数据保存到数据库中
        spc = SpitComments()
        spc.author_id = author_id
        spc.spit_id = spit_id
        spc.create_time = time
        spc.content = data['content']
        spc.save()

        # 对吐槽表中的评论数增加1并保存
        spcc = Spit.objects.get(id=spit_id)
        spcc.comment_count += 1
        spcc.save()

        return Response({'msg': '评论成功'}, status=status.HTTP_201_CREATED)


class SpitLikeView(APIView):
    """点赞吐槽"""
    def post(self, request,*args,**kwargs):
        # 获取参数
        user_id = int(request.user.id)
        spit_id = int(self.kwargs['spit_id'])

        # 校验当前吐槽是否被当前用户点赞
        sp = SpitLike.objects.filter(user_id=user_id, spit_id=spit_id)

        # 未点赞过
        if not sp:
            # 将点赞的用户及对应的吐槽加入到数据库中
            spl = SpitLike()
            spl.user_id = user_id
            spl.spit_id = spit_id
            spl.save()

            # 将吐槽表中的点赞统计数据+1
            splc = Spit.objects.get(id=spit_id)
            splc.like_count += 1
            splc.save()
            return Response({'msg': '点赞成功'}, status=status.HTTP_201_CREATED)
        # 已点赞
        else:
            # 去除点赞统计
            sp.delete()
            # 将吐槽表中的点赞统计数据+1
            splc = Spit.objects.get(id=spit_id)
            splc.like_count -= 1
            splc.save()
            return Response({'msg': '取消点赞'})


class SpitCommentsLikeView(APIView):
    """点赞评论"""
    def post(self, request,*args,**kwargs):
        # 获取参数
        user_id = int(request.user.id)
        comment_id = int(self.kwargs['comment_id'])

        # 校验当前评论是否被当前用户点赞
        cl = CommentsLike.objects.filter(user_id=user_id, comment_id=comment_id)

        # 未点赞过
        if not cl:
            # 将点赞的用户及对应的评论加入到数据库中
            coml = CommentsLike()
            coml.user_id = user_id
            coml.comment_id = comment_id
            coml.save()

            # 将评论表中的点赞统计数据+1
            comlc = SpitComments.objects.get(id=comment_id)
            comlc.like_count += 1
            comlc.save()
            return Response({'msg': '点赞成功'}, status=status.HTTP_201_CREATED)

        else:
            # 去除点赞统计
            cl.delete()
            # 将评论表中的点赞统计数据-1
            comlc = SpitComments.objects.get(id=comment_id)
            comlc.like_count -= 1
            comlc.save()
            return Response({'msg': '取消点赞'})


class SpitCollectView(CreateAPIView):
    """收藏吐槽"""
    serializer_class = SpitCollectionsSerializer
